package com.scau.classOnline.controller;

import com.scau.classOnline.common.UserUtils;
import com.scau.classOnline.dto.UserDTO;
import com.scau.classOnline.entity.User;
import com.scau.classOnline.model.RespEntity;
import com.scau.classOnline.service.UserService;
import com.scau.classOnline.sftp.FTPClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


/**
 * Create by ji on 2019-07-09
 */
@RestController
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private FTPClient ftpClient;

    @GetMapping("/get")
    private RespEntity getUserById(@RequestParam("id") Integer id) {
        return RespEntity.ok(userService.getUserDetailModelById(id));
    }

    @PostMapping("/update")
    private RespEntity modifyUserById(@RequestParam(value = "pic",required = false) MultipartFile pic,
                                      UserDTO userDTO) {
        if (pic!=null){
            String picUrl=getPicUrl(pic);
            userDTO.setIconUrl(picUrl);
        }
        if(userService.modifyUserModelById(userDTO)){
            User user = userService.findByUserId(userDTO.getId());
            System.out.println(user);
            return RespEntity.ok("个人信息更改成功！",user);
        }else {
            return RespEntity.error("个人信息更新失败！");
        }
    }

    private String getPicUrl(MultipartFile pic) {
        String picPath = ftpClient.getRemotePicPath();
        String picRoute = picPath.substring(picPath.lastIndexOf("/"));
        String filename = pic.getOriginalFilename();
        filename=System.currentTimeMillis()+filename.substring(filename.lastIndexOf("."));//当前时间毫秒+文件后缀名
        ftpClient.upload(pic, picPath, filename);
        return "http://" + ftpClient.getHost() + picRoute + "/" + filename;
    }
}
